/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.tasks
{
	import com.qb9.flashlib.lang.assert;

	/**
	 * A task that will loop another given task.
	 *
	 * @see TaskRunner
	 */
	public class Loop extends Queue
	{
		private var backupTask:ITask;
		public var remainingLoops:uint;

		public function Loop(task:ITask, loops:int = -1)
		{
			autoStartAddedTasks = true;
			backupTask = task.clone();
			remainingLoops = loops;
		}
		
		protected override function startNext():void
		{
			if (remainingLoops != 0)
			{
				if (empty)
				{
					add(backupTask.clone());
					super.startNext();
				}
				assert(subtasks.length <= 1);
			}
			else
				this.taskComplete();
		}
		
		protected override function onSubTaskComplete(ev:TaskEvent):void
		{
			if (remainingLoops > 0)
				remainingLoops--;
			super.onSubTaskComplete(ev);
		}

		/** @inheritDoc */
		public override function dispose():void
		{
			backupTask.dispose();
			super.dispose();
		}

		/** @inheritDoc */
		public override function clone():ITask
		{
			return new Loop(backupTask, remainingLoops);
		}
	}
}

